package com.hexb.core.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Package : com.feitian.xstream.oathu2.config
 * @Author : hexb
 * @Date : 2018-08-21 12:09
 */
@Configuration
@ConditionalOnProperty(value = "project.crossDomain", havingValue = "true")
public class CrossConfig {

    @Value("${project.exposedHeaders:}")
    private String exposedHeaders;

    @Bean
    @ConditionalOnProperty(value = "project.crossDomain", havingValue = "true")
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        if(!StringUtils.isEmpty(exposedHeaders)){
            corsConfiguration.addExposedHeader(exposedHeaders);
        }
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
